package inventory.shiro.filter;

import inventory.common.ResultData;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class MyAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyAuthenticationFilter.class);

    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //与resultData对应
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setStatus(200);
        try {
            //设置返回信息
            PrintWriter out = httpServletResponse.getWriter();
            ResultData resultData = new ResultData().FAILD().setResultIns("登录失败");
            out.write(JSONObject.fromObject(resultData).toString());
            out.flush();
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        super.saveRequestAndRedirectToLogin(request,httpServletResponse);
    }

    public MyAuthenticationFilter() {
        super();
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        System.out.println("进入跨域设置");
        /*因跨域后session不一致，添加代码 begin ----*/
        HttpServletRequest request2 = (HttpServletRequest) request;
        HttpServletResponse response2 = (HttpServletResponse) response;
        response2.setHeader("Access-Control-Allow-Origin", request2.getHeader("Origin"));
        response2.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response2.setHeader("Access-Control-Max-Age", "3600");
        response2.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response2.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
        /* ----end----*/
        return super.onPreHandle(request2, response2, mappedValue);
    }

    /**
     * 放行 option
     */
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
        System.out.println("进入了shiro自定义的filter");
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String method = servletRequest.getMethod();
        log.info("method:{},OPTIONS:{}",method, RequestMethod.OPTIONS.name());
        System.out.println("");
        if ( ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }

        return super.isAccessAllowed(request, response, mappedValue);
    }

    /**
     * 处理登录失败的异常
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //与resultData对应
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setStatus(200);
        try {
            //设置返回信息
            PrintWriter out = httpServletResponse.getWriter();
            ResultData resultData = new ResultData().FAILD().setResultIns(e.getMessage());
            out.write(JSONObject.fromObject(resultData).toString());
            out.flush();
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return super.onLoginFailure(token, e, request, httpServletResponse);
    }




}